//
//  ErrorHandleVC.swift
//  swiftDemo
//
//  Created by yaqiang bi on 2017/3/28.
//  Copyright © 2017年 毕小强. All rights reserved.
//

import UIKit

class ErrorHandleVC: UIViewController {
    enum VendingMachineError:Error{
        case invalidSelection                       //选择无效
        case insufficientFunds(coinsNeeded: Int)    //金额不足
        case outOfStock                             //缺货
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        
        let favoriteSnacks = [
            "Alice": "Chips",
            "Bob": "Licorice",
            "Eve": "Pretzels",
            ]
        func buyFavoriteSnack(person: String, vendingMachine: VendingMachine) throws {
            let snackName = favoriteSnacks[person] ?? "Candy Bar"
            try vendingMachine.vend(itemNamed: snackName)
        }

        let vendingMachine = VendingMachine()
        vendingMachine.coinsDeposited = 8
        do {
            try buyFavoriteSnack(person: "Eve", vendingMachine: vendingMachine)
            print("no errors")
        } catch VendingMachineError.invalidSelection {
            print("Invalid Selection.")
        } catch VendingMachineError.outOfStock {
            print("Out of Stock.")
        } catch VendingMachineError.insufficientFunds(let coinsNeeded) {
            print("Insufficient funds. Please insert an additional \(coinsNeeded) coins.")
        }catch{
            print("未知错误被抛出")
        }
        
        func someThrowingFuncution() throws->Int{
            return 1
        }
        
        let x = try? someThrowingFuncution()
        let y:Int?
        do{
            y = try someThrowingFuncution()
        }catch{
            y = nil
        }
        print(x ?? 2)
        print(y ?? 2)
        
        
        
        class Read{
            func readLine() throws ->Int{
                print("Read is use")
                return 100
            }
        }
        
        func exits(_ fileName:String) ->Bool{
            print("exits \(fileName)")
            return !fileName.isEmpty
        }
        
        func open(_ fileName:String)->Read?{
            print("Open \(fileName)")
            return Read()
        }
        
        func close(_ fileName:String){
            print("Close \(fileName)")
        }
        //defer 指定清理操作
        func processFile(fileName:String) throws{
            if exits(fileName) {
                let file = open(fileName)
                
                defer {
                    close(fileName)
                }
                if let line = try file?.readLine() {
                    //处理文件
                    print(line)
                }
            }

        }
        
        do{
            try processFile(fileName: "哈哈哈")
            print("没有错误?")
        }catch{
            print("这里有错误啊")
        }
        // Do any additional setup after loading the view.
    }

    struct Item {
        var price:Int
        var count:Int
    }
    
    class VendingMachine {
        var inventory = [
            "Candy Bar":Item(price:12,count:7),
            "Chips":Item(price:10,count:4),
            "Pretzels":Item(price: 7, count: 11)
        ]
        
        var coinsDeposited = 0
        func dispenseSnack(snack:String)  {
            print("Dispensing \(snack)")
        }
        
        func vend(itemNamed name:String) throws {
            guard let item = inventory[name] else {
                throw VendingMachineError.invalidSelection
            }
            
            guard item.count > 0 else {
                throw VendingMachineError.outOfStock
            }
            
            guard item.price <= coinsDeposited else {
                throw VendingMachineError.insufficientFunds(coinsNeeded: (item.price-coinsDeposited))
            }
            
            coinsDeposited -= item.price
            
            var newItem = item
            newItem.count -= 1
            inventory[name] = newItem
            
            print("Dispensing\(name)")
            
        }
    }
    

    
    struct PurchasedSnack {
        let name:String
        init(name:String,vendingMachine:VendingMachine) throws {
            try vendingMachine.vend(itemNamed: name)
            self.name = name
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
